package com.fll.codeworld.util;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author fff
 * 导出txt
 */
public class ParseJsonUtil {
    public static void writeToJson(HttpServletResponse response, String jsonString, String fileName) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        response.addHeader("Content-Disposition", "attachment;filename=" + getAttachmentFileName(fileName, fileName) + ".json");
        BufferedOutputStream buff = null;
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            buff = new BufferedOutputStream(outputStream);
            buff.write(jsonString.getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                buff.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成导出文件中文名,解决乱码问题
     *
     * @param fileName
     * @param defaultName
     * @return
     */
    private static String getAttachmentFileName(String fileName, String defaultName) {
        try {
            fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return defaultName;
        }
        return fileName;
    }


    /**
     * 读取json文件
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            if(jsonFile==null){
                return null;
            }
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
